import React, { FC, useState, MouseEvent } from "react";
import { Spin } from 'antd'
import styles from './EditCanvas.module.scss'
import { useDispatch, useSelector } from "react-redux";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import { getComponetConfByType } from "../../../components/QuestionComponents";
import { ComponentInfoType, changeSelectedId } from "../../../store/componentsReducer"
import { StateType } from "../../../store"
import { ComponentsStateType } from '../../../store/componentsReducer'

type PropsType = {
    loading: boolean
}

//选中组件改变颜色
const EditCanvas: FC<PropsType> = ({ loading }) => {
    const { componentList } = useGetComponentInfo()
    const dispatch = useDispatch()
    const { selectedId } = useSelector<StateType>(state => state.components) as ComponentsStateType
    function handleClick(event: MouseEvent, id: string) {
        event.stopPropagation()
        dispatch(changeSelectedId(id))
    }
    //获取组件信息*/
    function getComponent(componentInfo: ComponentInfoType, fe_id: string) {
        const { type, props } = componentInfo
        const componentConf = getComponetConfByType(type)
        if (componentConf == null) return null
        else {
            const { Component } = componentConf
            return <div onClick={(e) => handleClick(e, fe_id)} className={`${styles["comoponten-wrapper"]} ${selectedId == fe_id ? styles.selected : ''}`} key={fe_id}>
                <div className={styles.comoponent}>
                    <Component {...props} />
                </div>
            </div>
        }
    }
    if (loading) return <div><Spin /></div>
    return <div className={styles.canvas}>
        {componentList.map(c => {
            const { fe_id } = c
            return getComponent(c, fe_id)
        })}
    </div>
}

export default EditCanvas